package org.luckyjourney.service.booking.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.PageHelper;
import com.sun.org.apache.bcel.internal.generic.NEW;
import org.checkerframework.checker.units.qual.A;
import org.luckyjourney.config.QiNiuConfig;
import org.luckyjourney.entity.File;
import org.luckyjourney.entity.booking.*;
import org.luckyjourney.entity.booking.dto.OrdersCancelDTO;
import org.luckyjourney.entity.booking.dto.OrdersDTO;
import org.luckyjourney.entity.booking.vo.AmountWithdrawnVO;
import org.luckyjourney.entity.booking.vo.BookingVO;
import org.luckyjourney.entity.booking.vo.OrderVO;
import org.luckyjourney.entity.plan.PlanType;
import org.luckyjourney.entity.plan.dto.PlanDTO;
import org.luckyjourney.entity.plan.vo.PlanVO;
import org.luckyjourney.entity.regularusers.RegularUsers;
import org.luckyjourney.entity.user.User;
import org.luckyjourney.exception.BaseException;
import org.luckyjourney.mapper.booking.*;
import org.luckyjourney.mapper.plan.ConsultantsPlanMapper;
import org.luckyjourney.mapper.plan.PlanTypeMapper;
import org.luckyjourney.mapper.regularusers.RegularUsersMapper;
import org.luckyjourney.mapper.user.UserMapper;
import org.luckyjourney.service.FileService;
import org.luckyjourney.service.booking.OrdersService;
import org.luckyjourney.util.BaseContext;
import org.luckyjourney.util.PageResult;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;


@Service
public class OrdersServiceImpl implements OrdersService {
    @Autowired
    OrdersMapper ordersMapper;
    @Autowired
    RegularUsersMapper regularUsersMapper;
    @Autowired
    BookingMapper bookingMapper;
    @Autowired
    FileService fileService;
    @Autowired
    AmountWithdrawnMapper amountWithdrawnMapper;
    @Autowired
    ConsultantsPlanMapper consultantsPlanMapper;
    @Autowired
    PlanTypeMapper planTypeMapper;
    @Autowired
    TableRevenueMapper tableRevenueMapper;
    @Autowired
    OrderInquiriesMapper orderInquiriesMapper;

    @Override
    public void CancelOrder(OrdersCancelDTO ordersCancelDTO) {
        //获得订单id
        Orders orders = new Orders();
        //获得订单id
        orders.setId(ordersCancelDTO.getId());
        orders.setStatus(Orders.CANCELLED);
        //取消原因
        String cancelReason = ordersCancelDTO.getCancelReason();
        orders.setCancelReason(cancelReason);

        orders.setCancelTime(LocalDateTime.now());
        ordersMapper.update(orders);
    }

    @Override
    public OrderVO DetailsOrder(OrdersCancelDTO ordersCancelDTO) {

        Long id = ordersCancelDTO.getId();
        if (ObjectUtil.isEmpty(id)) {
            throw new BaseException("请选择要查看的订单");
        }

        OrderVO orderVO = ordersMapper.select(id);
        OrderVO orderVO1 = getOrderVO(orderVO);
        return orderVO1;
    }

    private OrderVO getOrderVO(OrderVO orderVO) {
        //获取用户头像
        OrderVO orderVO1 = new OrderVO();
        BeanUtils.copyProperties(orderVO, orderVO1);
        Long bookingId = orderVO.getBookingId();
        Long classifyId = orderVO.getClassifyId();
        PlanType planType = new PlanType();
        planType.setId(classifyId);
        Long currentId = BaseContext.getCurrentId();
        //根本订单中是那个咨询师
        planType.setUserId(currentId);
        List<PlanType> planType1 = planTypeMapper.selectId(planType);
        for (PlanType type : planType1) {
            //咨询的类型
            String type1 = type.getType();
            orderVO1.setType(type1);
        }
        if (ObjectUtil.isNotEmpty(bookingId)) {
            Booking booking = new Booking();
            booking.setId(bookingId);
            booking.setRegularId(currentId);
            BookingVO bookingVO = bookingMapper.selectPersonal(booking);
            if (ObjectUtil.isNotEmpty(bookingVO)) {
                Integer planId = bookingVO.getPlanId();
                if (ObjectUtil.isNotEmpty(planId)) {
                    PlanVO planVO = consultantsPlanMapper.selectId(planId);

                    if (ObjectUtil.isNotEmpty(planVO)) {
                        //设置的金额
                        BigDecimal originallyPrice = planVO.getPrice();
                        orderVO1.setOriginallyPrice(originallyPrice);
                        String serviceMode = planVO.getServiceMode();
                        System.out.println("serviceMode = " + serviceMode);
                        if (ObjectUtil.isNotEmpty(serviceMode)) {
                            if (serviceMode.equals("语音")) {
                                orderVO1.setService(-1);
                                orderVO1.setServiceMode("语音");
                            }
                            if (serviceMode.equals("视频")) {
                                orderVO1.setService(1);
                                orderVO1.setServiceMode("视频");
                            }
                            if (serviceMode.equals("面对面")) {
                                orderVO1.setService(2);
                                orderVO1.setServiceMode("面对面");
                            }
                        }
                        String planDate = planVO.getPlanDate();
                        String planTime = planVO.getPlanTime();
                        orderVO1.setPlanDate(planDate);
                        orderVO1.setPlanTime(planTime);
                    }
                }
            }
        }
        //获取咨询是id
        Long userId = orderVO.getUserId();
        RegularUsers regularUsers = regularUsersMapper.selectById(userId);

        if (ObjectUtil.isNotEmpty(regularUsers.getAvatar())) {
            File file = fileService.getById(regularUsers.getAvatar());
            String a = QiNiuConfig.CNAME + "/" + file.getFileKey();
            orderVO1.setA(a);
            orderVO1.setAvatar(file.getId());
        }
        return orderVO1;
    }

    @Override
    public void DelectOrder(OrdersCancelDTO ordersCancelDTO) {

        Long id = ordersCancelDTO.getId();
        if (ObjectUtil.isEmpty(id)) {
            throw new BaseException("请选择要删除的订单");
        }

        ordersMapper.delect(id);

    }

    @Override
    public Page<OrderVO> selectPage(OrdersDTO ordersDTO) {
        Page<OrderVO> orderVOPage = new Page<>();
        Integer page = ordersDTO.getPage();
        Integer pages=page-1;
        Integer pageSize = ordersDTO.getPageSize();
        if (ObjectUtil.isEmpty(page) && ObjectUtil.isEmpty(pageSize)) {
            throw new BaseException("页码数和每页条数不能为空");
        }
        Long currentId = BaseContext.getCurrentId();
        ordersDTO.setRegularId(currentId);
        ordersDTO.setPage(pages);
        List<OrderVO> orderVOS = ordersMapper.selectPage(ordersDTO);
        List<OrderVO> counts = ordersMapper.selectCounts(ordersDTO);
        ArrayList<OrderVO> voArrayList = new ArrayList<>();
        for (OrderVO orderVO : orderVOS) {
            Long id = orderVO.getId();
            OrderVO vo = ordersMapper.select(id);
            OrderVO orderVO1 = getOrderVO(currentId, orderVO, vo);
            voArrayList.add(orderVO1);
        }
        orderVOPage.setRecords(voArrayList);
        orderVOPage.setTotal(counts.size());
        return orderVOPage;
    }

    private OrderVO getOrderVO(Long currentId, OrderVO orderVO, OrderVO vo) {
        //获取用户头像
        OrderVO orderVO1 = new OrderVO();
        BeanUtils.copyProperties(vo, orderVO1);
        Long bookingId = orderVO.getBookingId();
        Long classifyId = orderVO.getClassifyId();
        PlanType planType = new PlanType();
        planType.setId(classifyId);
        //根本订单中是那个咨询师
        planType.setUserId(currentId);
        List<PlanType> planType1 = planTypeMapper.selectId(planType);
        for (PlanType type : planType1) {
            //咨询的类型
            String type1 = type.getType();
            orderVO1.setType(type1);
        }
        if (ObjectUtil.isNotEmpty(bookingId)) {
            Booking booking = new Booking();
            booking.setId(bookingId);
            booking.setRegularId(currentId);
            BookingVO bookingVO = bookingMapper.selectPersonal(booking);
            if (ObjectUtil.isNotEmpty(bookingVO)) {
                Integer planId = bookingVO.getPlanId();
                if (ObjectUtil.isNotEmpty(planId)) {
                    PlanVO planVO = consultantsPlanMapper.selectId(planId);

                    if (ObjectUtil.isNotEmpty(planVO)) {
                        //设置的金额
                        BigDecimal originallyPrice = planVO.getPrice();
                        orderVO1.setOriginallyPrice(originallyPrice);
                        String serviceMode = planVO.getServiceMode();
                        System.out.println("serviceMode = " + serviceMode);
                        if (ObjectUtil.isNotEmpty(serviceMode)) {
                            if (serviceMode.equals("语音")) {
                                orderVO1.setService(-1);
                                orderVO1.setServiceMode("语音");
                            }
                            if (serviceMode.equals("视频")) {
                                orderVO1.setService(1);
                                orderVO1.setServiceMode("视频");
                            }
                            if (serviceMode.equals("面对面")) {
                                orderVO1.setService(2);
                                orderVO1.setServiceMode("面对面");
                            }
                        }
                        String planDate = planVO.getPlanDate();
                        String planTime = planVO.getPlanTime();
                        orderVO1.setPlanDate(planDate);
                        orderVO1.setPlanTime(planTime);
                    }
                }
            }
        }
        //获取咨询是id
        Long userId = orderVO.getUserId();
        RegularUsers regularUsers = regularUsersMapper.selectById(userId);

        if (ObjectUtil.isNotEmpty(regularUsers.getAvatar())) {
            File file = fileService.getById(regularUsers.getAvatar());
            String a = QiNiuConfig.CNAME + "/" + file.getFileKey();
            orderVO1.setA(a);
            orderVO1.setAvatar(file.getId());
        }
        return orderVO1;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        OrdersDTO ordersDTO = new OrdersDTO();
        ordersDTO.setOrdersNumber(outTradeNo);
        ordersDTO.setRegularId(userId);
        // 根据订单号查询当前用户的订单
        Orders ordersDB = ordersMapper.getByNumberAndUserId(ordersDTO);
        if(ObjectUtil.isNotEmpty(ordersDB)){
            BigDecimal price = ordersDB.getPrice();
            Long psychologyId = ordersDB.getUserId();
            /**
             * 查询后添加记录防止重复添加
             */
            OrderInquiries orderInquiries=orderInquiriesMapper.select(outTradeNo);
            if(ObjectUtil.isEmpty(orderInquiries)){
                OrderInquiries orderInquiries1 = new OrderInquiries();
                orderInquiries1.setOrdersNumber(outTradeNo);
                orderInquiries1.setCreateTime(LocalDateTime.now());
                orderInquiriesMapper.insert(orderInquiries1);
                //咨询师可提现的金额
                AmountWithdrawnVO amountWithdrawnVO =amountWithdrawnMapper.selectAmountWithdrawn(psychologyId);
                if(ObjectUtil.isNotEmpty(amountWithdrawnVO)){
                    BigDecimal amount1 = amountWithdrawnVO.getAmount();
                    BigDecimal amount=amount1.add(price);
                    AmountWithdrawn amountWithdrawn = new AmountWithdrawn();
                    amountWithdrawn.setAmount(amount);
                    amountWithdrawn.setUserId(psychologyId);
                    amountWithdrawnMapper.updateAmountWithdrawn(amountWithdrawn);
                }else {
                    AmountWithdrawn amountWithdrawn = new AmountWithdrawn();
                    amountWithdrawn.setAmount(price);
                    amountWithdrawn.setUserId(psychologyId);
                    amountWithdrawnMapper.insertAmountWithdrawn(amountWithdrawn);
                }
                /**
                 * 咨询师收入明细
                 */
                TableRevenue tableRevenue1 = new TableRevenue();
                tableRevenue1.setRevenueAmount(price);
                tableRevenue1.setUserId(psychologyId);
                tableRevenue1.setCreateTime(LocalDateTime.now());
                tableRevenue1.setIncomeDescription("客户预约收入");
                tableRevenueMapper.insertTableRevenue(tableRevenue1);
            }

            // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
            Orders orders = Orders.builder()
                    .id(ordersDB.getId())
                    .status(Orders.TO_BE_CONFIRMED)
                    .paymentTime(LocalDateTime.now())
                    .build();

            ordersMapper.update(orders);
        }

    }

    @Override
    public void refundSuccess(String outTradeNo) {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        OrdersDTO ordersDTO = new OrdersDTO();
        ordersDTO.setRefundOrdersNumber(outTradeNo);
        ordersDTO.setRegularId(userId);
        // 根据订单号查询当前用户的订单
        Orders ordersDB = ordersMapper.getByNumberAndUserId(ordersDTO);
        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.CONFIRMED)
                .refundTime(LocalDateTime.now())
                .build();
        ordersMapper.update(orders);
    }


}
